package com.gec.zhs.component;

import com.gec.zhs.entity.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * @author zhs
 * @version 1.0
 * @date 2025-02-20
 * @description 利用springboot对redis的过期key监听的封装实现心跳检测机制
 */
@Component
@Slf4j
public class RedisKeyExpireListenerComponent extends KeyExpirationEventMessageListener {


    @Autowired
    private RedisComponent redisComponent;

    public RedisKeyExpireListenerComponent(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }


    //监听redis快过期的key
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = message.toString();
        if (!key.startsWith(Constants.REDIS_KEY_VIDEO_PLAY_COUNT_ONLINE_PREIFX + Constants.REDIS_KEY_VIDEO_PLAY_COUNT_USER_PREFIX)) {
            return;
        }
        //监听 在线用户过期的key
        //redis -> video:video:play:online:user: ySZE9nHIbKwHIa6R8Uvx  43d4daa8aa7e17e7abe3c73f32174113
        //userKeyIndex -> video:video:play:online:user:
        //fileId -> ySZE9nHIbKwHIa6R8Uvx
        Integer userKeyIndex = key.indexOf(Constants.REDIS_KEY_VIDEO_PLAY_COUNT_USER_PREFIX) + Constants.REDIS_KEY_VIDEO_PLAY_COUNT_USER_PREFIX.length();
        String fileId = key.substring(userKeyIndex, userKeyIndex + Constants.LENGTH_20);
        //计数器 人数-1
        redisComponent.decrementPlayOnlineCount(String.format(Constants.REDIS_KEY_VIDEO_PLAY_COUNT_ONLINE, fileId));
    }

    public static void main(String[] args) {
        //video:video:play:online:user:
        System.out.println(Constants.REDIS_KEY_VIDEO_PLAY_COUNT_ONLINE_PREIFX + Constants.REDIS_KEY_VIDEO_PLAY_COUNT_USER_PREFIX);
    }
}
